// middleware/authMiddleware.js
const jwt = require('jsonwebtoken');
const secretKey = process.env.JWT_SECRET; // 从环境变量中获取密钥

const authenticateToken = async (ctx, next) => {
  const whiteList = ['/users/login', '/users/register', '/contacts/save', '/news']; // 白名单路由

  // 检查是否在白名单中
  if (whiteList.includes(ctx.path) || ctx.method === 'OPTIONS') {
    return next();
  }
  const authHeader = ctx.headers.authorization;
  // console.log("authHeader", authHeader)
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    ctx.status = 401;
    ctx.body = { message: 'token已失效, 请重新登录' };
    return;
  }

  const token = authHeader.split(' ')[1];
  // console.log('token', token)
  try {
    const decoded = jwt.verify(token, secretKey);
    // console.log("decoded", decoded)
    ctx.state.user = decoded; // 将解码后的用户信息附加到 ctx.state
    await next();
  } catch (err) {
    console.error('JWT verification failed:', err);
    ctx.status = 403;
    ctx.body = { message: 'Invalid token.' };
  }
};

module.exports = authenticateToken;